import { Link, useNavigate } from 'react-router-dom';
import { useState, useMemo } from 'react';
import { ShoppingCart, Trash2, ArrowRight, Package, ChevronLeft, ChevronRight, User, Mail, MapPin, Globe, Lock, CreditCard, Eye, EyeOff } from 'lucide-react';
import { useCart } from '../../contexts/CartContext';
import { useLanguage } from '../../contexts/LanguageContext';
import { useLocalizedLink } from '../../hooks/useLocalizedLink';
import Button from '../../components/Button';
import { createEmailPasswordAccount } from '../../services/auth';
import { StripeCheckout } from '../../components/StripeCheckoutForm';
import { orderService } from '../../services/order';

const ITEMS_PER_PAGE = 5;

interface BillingDetails {
  fullName: string;
  email: string;
  address: string;
  country: string;
  postalCode: string;
}

const Cart = () => {
  const { items, removeItem, clearCart, getTotalPrice } = useCart();
  const { language } = useLanguage();
  const { getLink } = useLocalizedLink();
  const navigate = useNavigate();
  const [currentPage, setCurrentPage] = useState(1);
  const [showStripeCheckout, setShowStripeCheckout] = useState(false);
  const [isCreatingOrder, setIsCreatingOrder] = useState(false);
  
  // Billing details state
  const [billingDetails, setBillingDetails] = useState<BillingDetails>({
    fullName: '',
    email: '',
    address: '',
    country: '',
    postalCode: ''
  });
  
  // User registration state
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isRegistering, setIsRegistering] = useState(false);
  const [isRegistered, setIsRegistered] = useState(false);
  const [registrationError, setRegistrationError] = useState<string>('');
  
  // Coupon code state
  const [couponCode, setCouponCode] = useState('');
  const [appliedCoupon, setAppliedCoupon] = useState<string | null>(null);
  const [couponDiscount, setCouponDiscount] = useState(0);
  const [isCouponApplying, setIsCouponApplying] = useState(false);

  // Calculate pagination
  const totalPages = Math.ceil(items.length / ITEMS_PER_PAGE);
  const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
  const endIndex = startIndex + ITEMS_PER_PAGE;
  const currentItems = useMemo(() => items.slice(startIndex, endIndex), [items, startIndex, endIndex]);

  // Handle successful payment
  const handlePaymentSuccess = () => {
    clearCart();
    setShowStripeCheckout(false);
    alert(language === 'zh-CN' ? '支付成功！订单已提交。' : 'Payment successful! Order has been placed.');
  };

  // Handle place order (create order and navigate to Orders page)
  const handlePlaceOrder = async () => {
    setIsCreatingOrder(true);
    try {
      const orderItems = items.map(item => ({
        id: item.id,
        productType: item.productType,
        productName: getProductName(item.productType),
        quantity: typeof item.quantity === 'number' ? item.quantity : 1,
        price: item.totalPrice,
        period: item.period || '',
        traffic: item.traffic,
        ips: (item as any).ips,
      }));

      const result = await orderService.createOrder({
        items: orderItems,
        total: finalTotal,
        billingDetails: billingDetails,
        couponCode: appliedCoupon || undefined,
        discount: discountAmount,
      });

      if (result.success && result.order) {
        clearCart();
        const ordersPath = language === 'zh-CN' ? '/zh-CN/orders' : '/orders';
        navigate(`${ordersPath}?id=${result.order.id}`);
      } else {
        alert(result.error || (language === 'zh-CN' ? '创建订单失败' : 'Failed to create order'));
      }
    } catch (error) {
      console.error('Error creating order:', error);
      alert(language === 'zh-CN' ? '创建订单时出错' : 'Error creating order');
    } finally {
      setIsCreatingOrder(false);
    }
  };

  // Reset to page 1 if current page is out of bounds
  useMemo(() => {
    if (currentPage > totalPages && totalPages > 0) {
      setCurrentPage(totalPages);
    }
  }, [currentPage, totalPages]);

  // Apply coupon code
  const handleApplyCoupon = () => {
    setIsCouponApplying(true);
    
    // TODO: 实际调用后端 API 验证优惠码
    setTimeout(() => {
      const validCoupons: Record<string, number> = {
        'SAVE10': 0.10,      // 10% off
        'SAVE20': 0.20,      // 20% off
        'WELCOME': 0.15,     // 15% off
        'VIP': 0.25,         // 25% off
      };
      
      const discount = validCoupons[couponCode.toUpperCase()];
      
      if (discount) {
        setAppliedCoupon(couponCode.toUpperCase());
        setCouponDiscount(discount);
        alert(language === 'zh-CN' 
          ? `优惠码已应用！享受 ${(discount * 100).toFixed(0)}% 折扣`
          : `Coupon applied! Enjoy ${(discount * 100).toFixed(0)}% off`
        );
      } else {
        alert(language === 'zh-CN' ? '无效的优惠码' : 'Invalid coupon code');
      }
      
      setIsCouponApplying(false);
    }, 500);
  };

  // Remove coupon
  const handleRemoveCoupon = () => {
    setAppliedCoupon(null);
    setCouponDiscount(0);
    setCouponCode('');
  };

  // Calculate final price with discount
  const subtotal = getTotalPrice();
  const discountAmount = subtotal * couponDiscount;
  const finalTotal = subtotal - discountAmount;

  // Handle user registration
  const handleRegister = async () => {
    if (!billingDetails.email || !billingDetails.fullName) {
      alert(language === 'zh-CN' ? '请填写完整信息' : 'Please fill in all required fields');
      return;
    }
    
    setRegistrationError('');
    
    // Validate password
    if (password.length < 8) {
      setRegistrationError(language === 'zh-CN' ? '密码必须至少8个字符' : 'Password must be at least 8 characters');
      return;
    }
    
    if (password !== confirmPassword) {
      setRegistrationError(language === 'zh-CN' ? '两次输入的密码不一致' : 'Passwords do not match');
      return;
    }
    
    setIsRegistering(true);
    
    try {
      await createEmailPasswordAccount(billingDetails.email, password, billingDetails.fullName);
      setIsRegistered(true);
      alert(language === 'zh-CN' 
        ? '注册成功！账号已创建。' 
        : 'Registration successful! Account created.'
      );
    } catch (error: any) {
      console.error('Registration error:', error);
      setRegistrationError(error.message || (language === 'zh-CN' ? '注册失败' : 'Registration failed'));
      alert(language === 'zh-CN' ? `注册失败: ${error.message}` : `Registration failed: ${error.message}`);
    } finally {
      setIsRegistering(false);
    }
  };

  const getProductName = (productType: string) => {
    const names = {
      'dynamic-residential': {
        en: 'Dynamic Residential IPv6',
        'zh-CN': '动态住宅 IPv6',
      },
      'static-residential': {
        en: 'Static Residential IPv6',
        'zh-CN': '静态住宅 IPv6',
      },
      'datacenter': {
        en: 'Datacenter IPv6',
        'zh-CN': '数据中心 IPv6',
      },
    };
    return names[productType as keyof typeof names]?.[language] || productType;
  };

  const getPeriodLabel = (period?: string) => {
    if (!period) return '';
    const labels = {
      day: { en: 'Daily', 'zh-CN': '按天' },
      week: { en: 'Weekly', 'zh-CN': '按周' },
      month: { en: 'Monthly', 'zh-CN': '按月' },
      year: { en: 'Yearly', 'zh-CN': '按年' },
    };
    return labels[period as keyof typeof labels]?.[language] || period;
  };

  if (items.length === 0) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-12 transition-colors duration-300">
        <div className="container mx-auto px-4">
          <div className="max-w-4xl mx-auto">
            <h1 className="text-3xl font-bold text-[#0f1c3f] dark:text-white mb-8">
              {language === 'zh-CN' ? '购物车' : 'Shopping Cart'}
            </h1>

            <div className="bg-white dark:bg-gray-800 rounded-xl p-12 text-center shadow-lg">
              <div className="inline-flex items-center justify-center w-24 h-24 bg-gray-100 dark:bg-gray-700 rounded-full mb-6">
                <ShoppingCart className="text-gray-400 dark:text-gray-500" size={48} />
              </div>
              <h2 className="text-2xl font-bold text-[#0f1c3f] dark:text-white mb-4">
                {language === 'zh-CN' ? '购物车为空' : 'Your cart is empty'}
              </h2>
              <p className="text-gray-600 dark:text-gray-300 mb-8">
                {language === 'zh-CN'
                  ? '浏览我们的产品并添加您需要的服务'
                  : 'Browse our products and add the services you need'}
              </p>
              <Link to={getLink('/pricing')}>
                <Button variant="gradient">
                  {language === 'zh-CN' ? '查看定价' : 'View Pricing'}
                </Button>
              </Link>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-12 transition-colors duration-300">
      <div className="container mx-auto px-4">
        <div className="max-w-6xl mx-auto">
          <div className="flex justify-between items-center mb-8">
            <h1 className="text-3xl font-bold text-[#0f1c3f] dark:text-white">
              {language === 'zh-CN' ? '购物车' : 'Shopping Cart'}
              <span className="ml-3 text-lg font-normal text-gray-500 dark:text-gray-400">
                ({items.length} {language === 'zh-CN' ? '件商品' : 'items'})
              </span>
            </h1>
            <button
              onClick={clearCart}
              className="text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 flex items-center gap-2 transition-colors"
            >
              <Trash2 size={18} />
              {language === 'zh-CN' ? '清空购物车' : 'Clear Cart'}
            </button>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* Cart Items */}
            <div className="lg:col-span-2">
              <div className="space-y-4 mb-6">
                {currentItems.map((item) => (
                  <div
                    key={item.id}
                    className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-md border border-gray-200 dark:border-gray-700 transition-colors"
                  >
                    <div className="flex justify-between items-start">
                      <div className="flex-1">
                        <div className="flex items-start justify-between mb-4">
                          <div>
                            <h3 className="text-lg font-bold text-[#0f1c3f] dark:text-white mb-2">
                              {getProductName(item.productType)}
                            </h3>
                            <div className="space-y-1 text-sm text-gray-600 dark:text-gray-300">
                              {/* Dynamic Residential - Traffic */}
                              {item.productType === 'dynamic-residential' && item.traffic && (
                                <div className="flex items-center gap-2">
                                  <Package size={16} />
                                  <span>
                                    {language === 'zh-CN' ? '流量：' : 'Traffic: '}
                                    {item.traffic} GB
                                  </span>
                                </div>
                              )}

                            {/* Static Residential & Datacenter - Quantity, Period, Country */}
                            {(item.productType === 'static-residential' || item.productType === 'datacenter') && (
                              <>
                                {item.quantity && (
                                  <div>
                                    {language === 'zh-CN' ? '数量：' : 'Quantity: '}
                                    {item.quantity} IP{item.quantity > 1 ? 's' : ''}
                                  </div>
                                )}
                                {item.period && (
                                  <div>
                                    {language === 'zh-CN' ? '计费周期：' : 'Period: '}
                                    {getPeriodLabel(item.period)}
                                  </div>
                                )}
                                {item.countryName && (
                                  <div>
                                    {language === 'zh-CN' ? '国家：' : 'Country: '}
                                    {item.countryName}
                                  </div>
                                )}
                              </>
                            )}

                            {item.discount && item.discount > 0 && (
                              <div className="text-green-600 dark:text-green-400">
                                {language === 'zh-CN' ? '折扣：' : 'Discount: '}
                                {(item.discount * 100).toFixed(0)}% OFF
                              </div>
                            )}
                          </div>
                        </div>

                        <button
                          onClick={() => removeItem(item.id)}
                          className="text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 p-2 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
                          title={language === 'zh-CN' ? '移除' : 'Remove'}
                        >
                          <Trash2 size={18} />
                        </button>
                      </div>

                      <div className="flex justify-between items-center pt-4 border-t border-gray-200 dark:border-gray-700">
                        <div className="text-sm text-gray-500 dark:text-gray-400">
                          {language === 'zh-CN' ? '单价：' : 'Unit Price: '}
                          <span className="font-medium text-gray-900 dark:text-white">
                            ${item.unitPrice.toFixed(2)}
                          </span>
                        </div>
                        <div className="text-xl font-bold text-[#0f1c3f] dark:text-white">
                          ${item.totalPrice.toFixed(2)}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
              </div>

              {/* Pagination Controls */}
              {totalPages > 1 && (
                <div className="flex justify-center items-center gap-4 mt-6">
                  <button
                    onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                    disabled={currentPage === 1}
                    className="flex items-center gap-2 px-4 py-2 rounded-lg bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                  >
                    <ChevronLeft size={18} />
                    <span>{language === 'zh-CN' ? '上一页' : 'Prev'}</span>
                  </button>
                  
                  <span className="text-sm text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' 
                      ? `第 ${currentPage} 页，共 ${totalPages} 页` 
                      : `Page ${currentPage} of ${totalPages}`}
                  </span>
                  
                  <button
                    onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                    disabled={currentPage === totalPages}
                    className="flex items-center gap-2 px-4 py-2 rounded-lg bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                  >
                    <span>{language === 'zh-CN' ? '下一页' : 'Next'}</span>
                    <ChevronRight size={18} />
                  </button>
                </div>
              )}

              {/* Billing Details */}
              <div className="mt-8 bg-white dark:bg-gray-800 rounded-xl p-6 shadow-md border border-gray-200 dark:border-gray-700">
                <div className="flex items-center gap-2 mb-6">
                  <User className="text-[#00d4ff]" size={24} />
                  <h2 className="text-2xl font-bold text-[#0f1c3f] dark:text-white">
                    {language === 'zh-CN' ? '账单信息' : 'Billing Details'}
                  </h2>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {/* Full Name */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      {language === 'zh-CN' ? '姓名' : 'Full Name'} *
                    </label>
                    <div className="relative">
                      <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                      <input
                        type="text"
                        value={billingDetails.fullName}
                        onChange={(e) => setBillingDetails({ ...billingDetails, fullName: e.target.value })}
                        placeholder={language === 'zh-CN' ? '请输入您的姓名' : 'Enter your full name'}
                        className="w-full pl-10 pr-4 py-3 bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#00d4ff] focus:border-transparent text-gray-900 dark:text-white transition-all"
                        required
                      />
                    </div>
                  </div>

                  {/* Email */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      {language === 'zh-CN' ? '邮箱' : 'Email'} *
                    </label>
                    <div className="relative">
                      <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                      <input
                        type="email"
                        value={billingDetails.email}
                        onChange={(e) => setBillingDetails({ ...billingDetails, email: e.target.value })}
                        placeholder={language === 'zh-CN' ? '请输入您的邮箱' : 'Enter your email'}
                        className="w-full pl-10 pr-4 py-3 bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#00d4ff] focus:border-transparent text-gray-900 dark:text-white transition-all"
                        required
                        disabled={isRegistered}
                      />
                    </div>
                  </div>

                  {/* Address */}
                  <div className="md:col-span-2">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      {language === 'zh-CN' ? '地址' : 'Address'} *
                    </label>
                    <div className="relative">
                      <MapPin className="absolute left-3 top-3 text-gray-400" size={18} />
                      <input
                        type="text"
                        value={billingDetails.address}
                        onChange={(e) => setBillingDetails({ ...billingDetails, address: e.target.value })}
                        placeholder={language === 'zh-CN' ? '请输入您的地址' : 'Enter your address'}
                        className="w-full pl-10 pr-4 py-3 bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#00d4ff] focus:border-transparent text-gray-900 dark:text-white transition-all"
                        required
                      />
                    </div>
                  </div>

                  {/* Country */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      {language === 'zh-CN' ? '国家' : 'Country'} *
                    </label>
                    <div className="relative">
                      <Globe className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                      <input
                        type="text"
                        value={billingDetails.country}
                        onChange={(e) => setBillingDetails({ ...billingDetails, country: e.target.value })}
                        placeholder={language === 'zh-CN' ? '请输入国家' : 'Enter country'}
                        className="w-full pl-10 pr-4 py-3 bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#00d4ff] focus:border-transparent text-gray-900 dark:text-white transition-all"
                        required
                      />
                    </div>
                  </div>

                  {/* Postal Code */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      {language === 'zh-CN' ? '邮编' : 'Postal Code'} *
                    </label>
                    <input
                      type="text"
                      value={billingDetails.postalCode}
                      onChange={(e) => setBillingDetails({ ...billingDetails, postalCode: e.target.value })}
                      placeholder={language === 'zh-CN' ? '请输入邮编' : 'Enter postal code'}
                      className="w-full px-4 py-3 bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#00d4ff] focus:border-transparent text-gray-900 dark:text-white transition-all"
                      required
                    />
                  </div>
                </div>

                {/* OTP Verification */}
                <div className="mt-6 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
                  <div className="flex items-center gap-2 mb-3">
                    <Lock className="text-blue-600 dark:text-blue-400" size={20} />
                    <h3 className="font-semibold text-blue-900 dark:text-blue-100">
                      {language === 'zh-CN' ? '账户注册' : 'Account Registration'}
                    </h3>
                  </div>
                  
                  {!isRegistered ? (
                    <div className="space-y-4">
                      <p className="text-sm text-blue-700 dark:text-blue-300">
                        {language === 'zh-CN' 
                          ? '创建账户以完成结账'
                          : 'Create an account to complete checkout'}
                      </p>
                      
                      {registrationError && (
                        <div className="p-2 bg-red-100 dark:bg-red-900/20 border border-red-300 dark:border-red-800 rounded text-sm text-red-700 dark:text-red-400">
                          {registrationError}
                        </div>
                      )}
                      
                      {/* Password Field */}
                      <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                          {language === 'zh-CN' ? '密码' : 'Password'}
                        </label>
                        <div className="relative">
                          <input
                            type={showPassword ? 'text' : 'password'}
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            placeholder={language === 'zh-CN' ? '至少8个字符' : 'At least 8 characters'}
                            className="w-full px-4 py-2 pr-10 bg-white dark:bg-gray-800 border border-blue-300 dark:border-blue-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-white"
                          />
                          <button
                            type="button"
                            onClick={() => setShowPassword(!showPassword)}
                            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                          >
                            {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                          </button>
                        </div>
                      </div>
                      
                      {/* Confirm Password Field */}
                      <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                          {language === 'zh-CN' ? '确认密码' : 'Confirm Password'}
                        </label>
                        <div className="relative">
                          <input
                            type={showConfirmPassword ? 'text' : 'password'}
                            value={confirmPassword}
                            onChange={(e) => setConfirmPassword(e.target.value)}
                            placeholder={language === 'zh-CN' ? '再次输入密码' : 'Re-enter password'}
                            className="w-full px-4 py-2 pr-10 bg-white dark:bg-gray-800 border border-blue-300 dark:border-blue-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-white"
                          />
                          <button
                            type="button"
                            onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                          >
                            {showConfirmPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                          </button>
                        </div>
                      </div>
                      
                      <button
                        onClick={handleRegister}
                        disabled={!billingDetails.email || !billingDetails.fullName || !password || !confirmPassword || isRegistering}
                        className="w-full px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed font-medium"
                      >
                        {isRegistering 
                          ? (language === 'zh-CN' ? '注册中...' : 'Registering...') 
                          : (language === 'zh-CN' ? '创建账户' : 'Create Account')
                        }
                      </button>
                    </div>
                  ) : (
                    <div className="flex items-center gap-2 text-green-700 dark:text-green-400">
                      <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                      </svg>
                      <span className="font-medium">
                        {language === 'zh-CN' ? '账户已创建' : 'Account created'}
                      </span>
                    </div>
                  )}
                </div>
              </div>

              {/* Payment Method */}
              <div className="mt-8 bg-white dark:bg-gray-800 rounded-xl p-6 shadow-md border border-gray-200 dark:border-gray-700">
                <div className="flex items-center gap-2 mb-6">
                  <CreditCard className="text-[#00d4ff]" size={24} />
                  <h2 className="text-2xl font-bold text-[#0f1c3f] dark:text-white">
                    {language === 'zh-CN' ? '支付方式' : 'Payment Method'}
                  </h2>
                </div>

                <div className="p-6 rounded-lg border-2 border-[#00d4ff] bg-blue-50 dark:bg-blue-900/20">
                  <div className="flex flex-col items-center gap-4">
                    {/* Stripe Logo */}
                    <svg viewBox="0 0 60 25" className="w-20 h-8">
                      <path fill="#635BFF" d="M59.64 14.28h-8.06c.19 1.93 1.6 2.55 3.2 2.55 1.64 0 2.96-.37 4.05-.95v3.32a8.33 8.33 0 0 1-4.56 1.1c-4.01 0-6.83-2.5-6.83-7.48 0-4.19 2.39-7.52 6.3-7.52 3.92 0 5.96 3.28 5.96 7.5 0 .4-.04 1.26-.06 1.48zm-5.92-5.62c-1.03 0-2.17.73-2.17 2.58h4.25c0-1.85-1.07-2.58-2.08-2.58zM40.95 20.3c-1.44 0-2.32-.6-2.9-1.04l-.02 4.63-4.12.87V5.57h3.76l.08 1.02a4.7 4.7 0 0 1 3.23-1.29c2.9 0 5.62 2.6 5.62 7.4 0 5.23-2.7 7.6-5.65 7.6zM40 8.95c-.95 0-1.54.34-1.97.81l.02 6.12c.4.44.98.78 1.95.78 1.52 0 2.54-1.65 2.54-3.87 0-2.15-1.04-3.84-2.54-3.84zM28.24 5.57h4.13v14.44h-4.13V5.57zm0-4.7L32.37 0v3.36l-4.13.88V.88zm-4.32 9.35v9.79H19.8V5.57h3.7l.12 1.22c1-1.77 3.07-1.41 3.62-1.22v3.79c-.52-.17-2.29-.43-3.32.86zm-8.55 4.72c0 2.43 2.6 1.68 3.12 1.46v3.36c-.55.3-1.54.54-2.89.54a4.15 4.15 0 0 1-4.27-4.24l.01-13.17 4.02-.86v3.54h3.14V9.1h-3.13v5.85zm-4.91.7c0 2.97-2.31 4.66-5.73 4.66a11.2 11.2 0 0 1-4.46-.93v-3.93c1.38.75 3.1 1.31 4.46 1.31.92 0 1.53-.24 1.53-1C6.26 13.77 0 14.51 0 9.95 0 7.04 2.28 5.3 5.62 5.3c1.36 0 2.72.2 4.09.75v3.88a9.23 9.23 0 0 0-4.1-1.06c-.86 0-1.44.25-1.44.9 0 1.85 6.29.97 6.29 5.88z"/>
                    </svg>
                    <div className="text-center">
                      <p className="font-bold text-lg text-[#0f1c3f] dark:text-white">
                        {language === 'zh-CN' ? 'Stripe 安全支付' : 'Stripe Secure Payment'}
                      </p>
                      <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                        {language === 'zh-CN' 
                          ? '支持 Visa、Mastercard、American Express 等主流信用卡'
                          : 'Accepts Visa, Mastercard, American Express, and more'}
                      </p>
                    </div>
                    <div className="w-3 h-3 bg-[#00d4ff] rounded-full"></div>
                  </div>
                </div>

                {/* Payment Security Info */}
                <div className="mt-4 p-4 bg-gray-50 dark:bg-gray-900 rounded-lg">
                  <div className="flex items-start gap-2">
                    <Lock size={16} className="text-green-600 mt-0.5" />
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                      {language === 'zh-CN'
                        ? '✓ PCI DSS 认证 | ✓ 256位SSL加密 | ✓ 3D Secure验证'
                        : '✓ PCI DSS Certified | ✓ 256-bit SSL Encryption | ✓ 3D Secure Verification'}
                    </p>
                  </div>
                </div>
              </div>
            </div>

            {/* Order Summary */}
            <div className="lg:col-span-1">
              <div className="bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-800 dark:to-gray-900 rounded-xl p-6 shadow-lg border border-gray-200 dark:border-[#00d4ff]/30 text-gray-900 dark:text-white sticky top-24">
                <h3 className="text-xl font-bold mb-6">
                  {language === 'zh-CN' ? '订单摘要' : 'Order Summary'}
                </h3>

                <div className="space-y-4 mb-6">
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-600 dark:text-gray-300">
                      {language === 'zh-CN' ? '商品数量' : 'Items'}:
                    </span>
                    <span className="font-medium">{items.length}</span>
                  </div>

                  <div className="flex justify-between text-sm">
                    <span className="text-gray-600 dark:text-gray-300">
                      {language === 'zh-CN' ? '小计' : 'Subtotal'}:
                    </span>
                    <span className="font-medium">${subtotal.toFixed(2)}</span>
                  </div>

                  {/* Coupon Code Section */}
                  <div className="border-t border-gray-300 dark:border-white/20 pt-4">
                    {!appliedCoupon ? (
                      <div className="space-y-2">
                        <label className="block text-xs text-gray-600 dark:text-gray-300 font-medium">
                          {language === 'zh-CN' ? '优惠码' : 'Coupon Code'}
                        </label>
                        <div className="flex gap-2">
                          <input
                            type="text"
                            value={couponCode}
                            onChange={(e) => setCouponCode(e.target.value.toUpperCase())}
                            placeholder={language === 'zh-CN' ? '输入优惠码' : 'Enter code'}
                            className="flex-1 px-3 py-2 bg-white dark:bg-white/10 border border-gray-300 dark:border-white/30 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#00d4ff] focus:border-transparent text-gray-900 dark:text-white placeholder-gray-400 text-sm"
                          />
                          <button
                            onClick={handleApplyCoupon}
                            disabled={!couponCode || isCouponApplying}
                            className="px-4 py-2 bg-[#00d4ff] hover:bg-[#00e5ff] text-[#0f1c3f] font-semibold rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed text-sm whitespace-nowrap"
                          >
                            {isCouponApplying 
                              ? (language === 'zh-CN' ? '应用中...' : 'Applying...') 
                              : (language === 'zh-CN' ? '应用' : 'Apply')
                            }
                          </button>
                        </div>
                      </div>
                    ) : (
                      <div className="space-y-2">
                        <div className="flex items-center justify-between p-2 bg-green-500/20 border border-green-500/30 rounded-lg">
                          <div className="flex items-center gap-2">
                            <svg className="w-4 h-4 text-green-400" fill="currentColor" viewBox="0 0 20 20">
                              <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                            </svg>
                            <span className="text-sm text-green-400 font-medium">{appliedCoupon}</span>
                          </div>
                          <button
                            onClick={handleRemoveCoupon}
                            className="text-xs text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white underline"
                          >
                            {language === 'zh-CN' ? '移除' : 'Remove'}
                          </button>
                        </div>
                      </div>
                    )}
                  </div>

                  {/* Discount Display */}
                  {appliedCoupon && (
                    <div className="flex justify-between text-sm">
                      <span className="text-green-400">
                        {language === 'zh-CN' ? '折扣' : 'Discount'} ({(couponDiscount * 100).toFixed(0)}%):
                      </span>
                      <span className="font-medium text-green-400">-${discountAmount.toFixed(2)}</span>
                    </div>
                  )}

                  <div className="border-t border-gray-300 dark:border-white/20 pt-4">
                    <div className="flex justify-between text-lg font-bold">
                      <span>{language === 'zh-CN' ? '总计' : 'Total'}:</span>
                      <span className="text-[#00d4ff]">${finalTotal.toFixed(2)}</span>
                    </div>
                  </div>
                </div>

                {/* Checkout Requirements */}
                <div className="mb-4 p-3 bg-gray-100 dark:bg-white/10 rounded-lg">
                  <p className="text-xs text-gray-600 dark:text-gray-300 mb-2">
                    {language === 'zh-CN' ? '完成支付前请确保：' : 'Before checkout, please ensure:'}
                  </p>
                  <ul className="space-y-1 text-xs">
                    <li className="flex items-center gap-2">
                      {billingDetails.fullName && billingDetails.email && billingDetails.address && billingDetails.country && billingDetails.postalCode ? (
                        <span className="text-green-400">✓</span>
                      ) : (
                        <span className="text-gray-400">○</span>
                      )}
                      <span className={billingDetails.fullName && billingDetails.email && billingDetails.address && billingDetails.country && billingDetails.postalCode ? 'text-gray-900 dark:text-white' : 'text-gray-400'}>
                        {language === 'zh-CN' ? '填写账单信息' : 'Fill billing details'}
                      </span>
                    </li>
                    <li className="flex items-center gap-2">
                      {isRegistered ? (
                        <span className="text-green-400">✓</span>
                      ) : (
                        <span className="text-gray-400">○</span>
                      )}
                      <span className={isRegistered ? 'text-gray-900 dark:text-white' : 'text-gray-400'}>
                        {language === 'zh-CN' ? '创建账户' : 'Create account'}
                      </span>
                    </li>
                    <li className="flex items-center gap-2">
                      <span className="text-green-400">✓</span>
                      <span className="text-gray-900 dark:text-white">
                        {language === 'zh-CN' ? '选择支付方式' : 'Select payment method'}
                      </span>
                    </li>
                  </ul>
                </div>

                <button
                  onClick={handlePlaceOrder}
                  disabled={isCreatingOrder || !isRegistered || !billingDetails.fullName || !billingDetails.email || !billingDetails.address || !billingDetails.country || !billingDetails.postalCode}
                  className="w-full mb-3 px-6 py-3 bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600 text-white rounded-lg font-semibold transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 shadow-lg"
                >
                  {isCreatingOrder ? (
                    <>
                      <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                      {language === 'zh-CN' ? '正在创建订单...' : 'Creating order...'}
                    </>
                  ) : (
                    <>
                      {language === 'zh-CN' ? '下单' : 'Place an Order'}
                      <ArrowRight size={18} />
                    </>
                  )}
                </button>

                <Link to={getLink('/pricing')}>
                  <button className="w-full text-center text-sm text-gray-300 hover:text-white transition-colors">
                    {language === 'zh-CN' ? '继续购物' : 'Continue Shopping'}
                  </button>
                </Link>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Stripe Checkout Modal */}
      <StripeCheckout
        isOpen={showStripeCheckout}
        onClose={() => setShowStripeCheckout(false)}
        amount={finalTotal}
        billingDetails={{
          fullName: billingDetails.fullName,
          email: billingDetails.email,
          address: billingDetails.address,
          postalCode: billingDetails.postalCode,
          country: billingDetails.country
        }}
        onSuccess={handlePaymentSuccess}
      />
    </div>
  );
};

export default Cart;
